<?php

namespace app\index\controller;

use think\exception\ValidateException;
use app\model\Users;
use app\model\Member;
use app\model\UsersRelation;
use app\model\Openid;
use app\model\MessageSms;
use app\model\Technical;
use app\model\Tuanzhang;
use app\model\Operatingcity;
use app\model\Store;

class LoginController extends Base
{
	//会员登录
	public function index()
	{
		$data = input('post.');
		$ptype = input('post.ptype', '', 'serach_in');
		if ($data['username'] == 'undefined') {
			$data['username'] = '';
		}
		if ($data['password'] == 'undefined') {
			$data['password'] = '';
		}
		if ($data['userphone'] == 'undefined') {
			$data['userphone'] = '';
		}
		if ($data['captcha'] == 'undefined') {
			$data['captcha'] = '';
		}
		if (empty($data['username'])) {
			$data['username'] = $data['tel'];
		}
		$data['username'] = trim($data['username']);

		if (!empty($data['userphone'])) {

			if (empty($data['captcha'])) {
				throw new ValidateException('请输入验证');
			}
			$res = $this->checkMemberphonecaptcha($data);
		} else {
			if (empty($data['username'])) {
				throw new ValidateException('请输入用户名');
			}

			if (empty($data['password'])) {
				throw new ValidateException('请输入密码');
			}
			$res = $this->checkMemberLogin($data);
		}

		if ($res) {
			$from = input('get.from', '', 'serach_in');
			if ($from != 'wxapp' && $from != 'mp') {
				$this->userInfo['openid'] = $res['telephone'];
			}
			$this->setAppToken($this->userInfo, $this->getAppToken());
			return $this->json(['msg' => '登录成功', 'data' => $res]);
		}
	}

	public function userlogin()
	{
		$data = input('post.');
		$ptype = input('post.ptype', '', 'serach_in');
		$data['ptype'] = $ptype;
		if ($data['username'] == 'undefined') {
			$data['username'] = '';
		}
		if ($data['password'] == 'undefined') {
			$data['password'] = '';
		}
		if ($data['userphone'] == 'undefined') {
			$data['userphone'] = '';
		}
		if ($data['captcha'] == 'undefined') {
			$data['captcha'] = '';
		}
		if (empty($data['username'])) {
			$data['username'] = $data['tel'];
		}
		$data['username'] = trim($data['username']);

		if (!empty($data['userphone'])) {

			if (empty($data['captcha'])) {
				throw new ValidateException('请输入验证');
			}
			$res = $this->checkUsersphonecaptcha($data);
		} else {

			if (empty($data['username'])) {
				throw new ValidateException('请输入用户名');
			}

			if (empty($data['password'])) {
				throw new ValidateException('请输入密码');
			}
			$res = $this->checkUserspasswordLogin($data);
		}

		if ($res) {
			$this->setAppToken($this->userInfo, $this->getAppToken());
			if ($res['is_founder'] == 1) {
				$reid = $res['id'];
				$uid = $res['uid'];
			} else {
				$reid = UsersRelation::getreidbyid($res, $ptype);
				$uid = $res['id'];
			}

			UsersRelation::create([
				'weid' => weid(),
				'ptype' => $ptype,
				'reid' => (int) $reid,
				'uid' => (int) $uid,
				'mid' => UID()
			]);

			return $this->json(['msg' => '登录成功', 'data' => $res]);
			Users::where('id', $res['id'])->update(['login_time' => time(), 'login_ip' => client_ip()]);
		}
	}

	//获取小程序手机号
	public function getphonenumber()
	{
		$code = input('post.code', '', 'serach_in');
		$phonedata = \app\samos\wechat\MiniProgram::getphonenumber($code);
		$data = Member::bindphonenumber($phonedata->phoneNumber);

		$phone = $this->logintype($phonedata->phoneNumber);
		if ($phone && $phone['status'] == 1) {
			$data['is_reg'] = 0;
		} else {
			$data['is_reg'] = 1;
		}

		return $this->json(['data' => $data]);
	}

	//验证会员密码登录
	private function checkMemberLogin($data)
	{
		$where['username'] = $data['username'];
		$info =	Member::where($where)->find();

		if (empty($info)) {
			$info =	Member::where('telephone', $data['username'])->find();
		}

		if ($info) {
			$info = $info->toArray();
			if ($info['password'] === pass_hash($data['password'], $info["salt"])) {
				unset($info['password']);
				unset($info["salt"]);

				if (!($info['status'])) {
					throw new ValidateException("该账户被禁用");
				}
			} else {
				throw new ValidateException("用户名或者密码不正确");
			}
		} else {
			throw new ValidateException("用户名不存在");
		}

		return $info;
	}
	//验证会员手机登录
	private function checkMemberphonecaptcha($data)
	{

		if ($data['captcha'] == $this->userInfo['captcha']) {
			$info = Member::bindphonenumber($data['userphone']);
			$phone = $this->logintype($data['userphone']);
			if ($phone && $phone['status'] == 1) {
				$info['is_reg'] = 0;
			} else {
				$info['is_reg'] = 1;
			}
		} else {
			throw new ValidateException("验证码不正确");
		}
		return $info;
	}
	//会员退出登录
	public function memberlogout()
	{

		$this->userInfo['openid'] = '';
		$this->setAppToken($this->userInfo, $this->getAppToken());

		return $this->json(['msg' => '退出成功', 'res' => $res]);
	}
	private function checkUsersLogin($info)
	{
		$ptype = input('post.ptype', '', 'serach_in');
		unset($info['password']);
		unset($info["salt"]);

		if (!($info['status'])) {
			throw new ValidateException("该账户被禁用");
		}
		if ($ptype == 'store' && empty($info['sid'])) {
			throw new ValidateException("这不是商户帐号");
		}
		if ($ptype == 'operatingcity' && empty($info['ocid'])) {
			throw new ValidateException("这不是代理帐号");
		}
		if ($ptype == 'tuanzhang' && empty($info['tzid'])) {
			throw new ValidateException("这不是社区帐号");
		}
		if ($ptype == 'technical' && empty($info['tid'])) {
			if (empty(Technical::where('uid', $info['id'])->find())) {
				throw new ValidateException("这不是师傅帐号");
			}
		}

		if ($ptype == 'admin') {
			if (empty($info['tid']) && empty($info['sid']) && empty($info['ocid'])  && empty($info['tzid'])) {
			} else {
				throw new ValidateException("这不是管理员帐号");
			}
		}

		return $info;
	}
	//验证会员密码登录
	private function checkUserspasswordLogin($data)
	{
		$where['username'] = $data['username'];
		$info =	Users::where($where)->find();

		if (empty($info)) {
			$info =	Users::where('mobile', $data['username'])->find();
		}

		if ($info) {
			$info = $info->toArray();
			if ($info['password'] === pass_hash($data['password'], $info["salt"])) {
				$info = $this->checkUsersLogin($info);
			} else {
				throw new ValidateException("用户名或者密码不正确");
			}
		} else {
			throw new ValidateException("用户名不存在");
		}

		return $info;
	}
	//验证用户手机登录
	private function checkUsersphonecaptcha($data)
	{

		if ($data['captcha'] == $this->userInfo['captcha']) {
			$info = $this->logintype($data['userphone']);

			if (empty($info)) {
				$info =	Users::where('mobile', $data['userphone'])->find();
			}
			if ($info) {
				if ($info['status'] == 1) {
					$info = $this->checkUsersLogin($info);
					$from = input('get.from', '', 'serach_in');
					if ($from != 'wxapp' && $from != 'mp') {
						$this->userInfo['useropenid'] = $data['userphone'];
					}
				} else {
					throw new ValidateException("该账户被禁用");
				}
			} else {
				throw new ValidateException("用户不存在");
			}
		} else {
			throw new ValidateException("验证码不正确");
		}

		return $info;
	}
	//手机短信验证码
	public function captcha()
	{
		$phone = input('post.phone', '', 'serach_in');
		if (!empty($phone)) {

			$ptype = input('post.ptype', '', 'serach_in');

			if ($ptype) {
				$info = $this->logintype($phone);
				if (empty($info)) {
					throw new ValidateException("用户不存在");
				}
			}

			$this->userInfo['captcha'] = rand(1111, 9999);
			$data = MessageSms::send_sms([
				'phone' => $phone,
				'param' => json_encode([
					'code' => $this->userInfo['captcha']
				])
			]);
			$this->setAppToken($this->userInfo, $this->getAppToken());
		}
		return $this->json(['msg' => '手机验证码发送成功', 'data' => $data]);
	}
	//用户退出登录
	public function logout()
	{
		$ptype = input('post.ptype', '', 'serach_in');
		if ($ptype) {
			$where['weid'] = weid();
			$where['ptype'] = $ptype;
			$where['mid'] = UID();
			$res = UsersRelation::where($where)->delete();
			//$sql = $res->getLastsql();
			$this->userInfo[$ptype] = '';
			$this->setAppToken($this->userInfo, $this->getAppToken());
		}
		return $this->json(['msg' => '退出成功', 'res' => $res]);
	}

	//用户注销
	public function delid()
	{
		Member::where('id', UID())->delete();
		return $this->json(['msg' => '注销成功']);
	}


	//手机登录
	public function logintype($tel)
	{
		$ptype = input('post.ptype', '', 'serach_in');
		if ($ptype == 'technical') {
			$res = Technical::where('tel', $tel)->where('weid', weid())->find()?->toArray();
			if ($res) {
				$res['is_founder'] = 1;
			}
		}
		if ($ptype == 'tuanzhang') {
			$res = Tuanzhang::where('tel', $tel)->where('weid', weid())->find()?->toArray();
			if ($res) {
				$res['is_founder'] = 1;
			}
		}
		if ($ptype == 'operatingcity') {
			$res = Operatingcity::where('tel', $tel)->where('weid', weid())->find()?->toArray();
			if ($res) {
				$res['is_founder'] = 1;
			}
		}
		if ($ptype == 'store') {
			$res = Store::where('tel', $tel)->where('weid', weid())->find()?->toArray();
			if ($res) {
				$res['is_founder'] = 1;
			}
		}
		if ($ptype == 'admin') {
			$res = Users::where('mobile', $tel)->where('weid', weid())->find()?->toArray();
		}
		if ($ptype == 'member') {
			$res['status'] = 1;
		}
		return $res;
	}
}
